package flexulous.view;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Observer;
import java.util.Observable;

import org.gjt.sp.util.Log;

import flexulous.Flexulous;
import flexulous.model.FlexulousModel;
import flexulous.util.FlexulousCompilerHelper;

public class FlexulousTargetsPanel extends JPanel implements Observer {
    private static Class TAG = FlexulousTargetsPanel.class;
    
    private Flexulous flex;
    private FlexulousModel model;
    
    private JScrollPane scrollPane;
    private Box container;
    private List<FlexulousTargetComponent> componentList;
    
    public FlexulousTargetsPanel(Flexulous flex, FlexulousModel model) {
        this.flex = flex;
        this.model = model;
        
        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        
        model.addObserver(this);
        
        componentList = new ArrayList<FlexulousTargetComponent>();
        
        container = new Box(BoxLayout.Y_AXIS);
        scrollPane = new JScrollPane(container);
        
        scrollPane.getViewport().setBackground(Color.WHITE);
        
        add(scrollPane);
        
        createTargetComponents();
    }
    
    private void createTargetComponents() {
        List<FlexulousCompilerHelper> helperList = model.getHelpers();
        for (FlexulousCompilerHelper helper : helperList) {
            FlexulousTargetComponent component = 
                new FlexulousTargetComponent(helper);
            container.add(component);
            JSeparator separator = new JSeparator();
            separator.setMaximumSize(new Dimension(500, 10));
            separator.setForeground(Color.BLACK);
            container.add(separator);
            componentList.add(component);
        }
        if(container.getComponentCount() > 0){
        	container.remove(container.getComponentCount() - 1);
        }
    }
    
    private void updateComponents() {
        componentList.clear();
        container.removeAll();
        container.validate();
        container.repaint();
        createTargetComponents();
    }
    
    public void update(Observable o, Object arg) {
        int updateFlag = (Integer)arg;
        
        switch (updateFlag) {
        case FlexulousModel.TARGET_ADDED:
        case FlexulousModel.TARGET_REMOVED:
            updateComponents();
            break;
        }
    }
}
